package com.sptpc.learnspring.controller;

import com.github.pagehelper.PageInfo;
import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.service.IDrinkService;
import com.sptpc.learnspring.vo.DrinkListVO;
import com.sptpc.learnspring.vo.DrinkVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;

    // 新建饮品
    @PostMapping(value = "/add", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public Drink addNewDrink(@RequestBody @Valid NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setCreateTime(LocalDate.now());
        drink = drinkService.addNewDrink(drink);
        log.info("创建成功");
        return drink;
    }

    // 查询所有饮品
    // 使用PageHelper实现分页
    @GetMapping("/")
    public PageInfo<Drink> listDrinks(int page, int size) {
        log.info("查询饮品菜单，第{}页，每页{}条", page, size);
        return drinkService.getAllDrinks(page, size);
    }

    // 查询指定饮品
    @GetMapping("/{id}")
    public DrinkVO getDrinkById(@PathVariable Long id) {
        log.info("查询饮品，id: {}", id);
        // 和jpa不同的是mybatis不会返回Optional类型
        return drinkService.getDrinkById(id);
    }

    // 更新指定饮品
    @PutMapping("/update")
    public Drink updateDrink(@RequestBody @Valid Drink updateDrink) {
        log.info("更新饮品，id：{}", updateDrink.getId());
        return drinkService.updateDrink(updateDrink);
    }

    // 查询饮品
    @PostMapping("/")
    public DrinkListVO searchDrinks(String key) {
        log.info("搜索饮品 key: {}", key);
        // 和JPA不同，在Mybatis中可以自己实现sql，所以前端无需再自己加%
        List<Drink> list = drinkService.searchDrinksByKey(key);
        DrinkListVO result = new DrinkListVO();
        result.setCount((long) list.size());
        result.setData(list);
        return result;
    }

}
